package com.iotproject.studyservice.utils;

import okhttp3.*;
import okhttp3.RequestBody;
import org.json.JSONException;

import java.io.IOException;

import org.json.JSONObject;
public class AccessTokenUtils {

    public static final String API_KEY = "fYHFCNvHxBqL4mfgxnAGfe76";
    public static final String SECRET_KEY = "SWM863XGYG6sZ579Ff0GZlSkElT8LBZp";

    public static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */
    public static String getAccessToken() throws IOException, JSONException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        String result = response.body().string();
        String access_token = new JSONObject(result).getString("access_token");
        return access_token;
    }

}
